package com.warrantyhotel.android.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.model.ForgotPasswordObject;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.ToastUtil;

public class LoginActivity extends Activity implements Receiver, OnKeyListener {

	// private static final String TAG = LoginActivity.class.getSimpleName();
	private static SharedPreferences prefs;
	private ProgressDialog progress;
	private CheckBox rememberMe;
	private EditText password;
	private EditText username;
	private TextView forgotPassword;
	private WarrantyApplication app;
	private static final int TYPE_EMAIL = 59;
	private DetachableResultReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_page);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		app = (WarrantyApplication) getApplication();

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		rememberMe = (CheckBox) findViewById(R.id.rememberMe);
		forgotPassword = (TextView) findViewById(R.id.forgot_password);
		password.setOnKeyListener(this);

		Resources res = getResources();
		CharSequence styledText = res.getText(R.string.forgot_password1);
		forgotPassword.setText(styledText, TextView.BufferType.SPANNABLE);

		// Intent loginIntent = new Intent(Intent.ACTION_SYNC, null, this,
		// UpdateIntentService.class);
		// loginIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER,
		// app.getReceiver());
		// loginIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE,
		// QueriesCodes.SUBMIT_PURCHASE);
		// startService(loginIntent);

	}

	@Override
	protected void onResume() {
		super.onResume();

		// filling field in case rememberMe is True
		if (prefs.contains(Keys._remembeMe) && prefs.getBoolean(Keys._remembeMe, false)) {
			username.setText(prefs.getString(Keys._username, null));
			password.setText(prefs.getString(Keys._password, null));
			rememberMe.setChecked(true);
		}

//		if (rememberMe.isChecked() && !TextUtils.isEmpty(username.getText().toString()) && !TextUtils.isEmpty(password.getText().toString())) {
//			doLogin();
//		}

	}

	public void onLoginOnClick(View view) {
		doLogin();
	}

	private void doLogin() {
		if (!validate(username) || !validate(password)) {
			ToastUtil.showText(this, getString(R.string.validate_error));
			return;
		} else {
			// Login
			progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);

			Intent loginIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
			loginIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
			loginIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.DO_LOGIN);
			loginIntent.putExtra(Keys._username, username.getText().toString().trim());
			loginIntent.putExtra(Keys._password, password.getText().toString().trim());
			loginIntent.putExtra(Keys._remembeMe, rememberMe.isChecked());
			startService(loginIntent);

		}
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			// do nothing
			break;
		case UpdateIntentService.STATUS_ERROR:
			if (null != progress)
				progress.dismiss();
			ToastUtil.showText(getApplicationContext(), resultData.getString(UpdateIntentService.ERROR_MESSAGE));
			break;

		case UpdateIntentService.STATUS_FINISHED:
			if (null != progress)
				progress.dismiss();
			if (resultData.containsKey(Keys._isLoginSuccess) && resultData.getBoolean(Keys._isLoginSuccess)) {
				final Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
				intent.putExtra(Keys._firstName, resultData.getString(Keys._firstName));
				intent.putExtra(Keys._lastName, resultData.getString(Keys._lastName));
				// TODO
				// executeUpdateQueries();

				final Editor edit = prefs.edit();
				edit.remove(Keys._firstName);
				edit.remove(Keys._lastName);

				// save user/pass
				edit.putString(Keys._cacheLogin, username.getText().toString().trim());
				edit.putString(Keys._cachePass, password.getText().toString().trim());
				edit.putString(Keys._firstName, resultData.getString(Keys._firstName));
				edit.putString(Keys._lastName, resultData.getString(Keys._lastName));
				edit.commit();
				// //////////////

				
				startActivity(intent);
				finish();

				app.startExpireSession(resultData.getLong(Keys._session_time));

			} else if (resultData.containsKey(Keys._isLoginSuccess) && !resultData.getBoolean(Keys._isLoginSuccess)) {
				// ToastUtil.showText(getApplicationContext(),
				// getString(R.string.credential_error));
				ToastUtil.showText(getApplicationContext(), resultData.getString(Keys._message));

			}

			if (resultData.containsKey(Keys._isPasswordForgot)) {
				ForgotPasswordObject forgotObj = resultData.getParcelable(Keys._isPasswordForgot);
				// if (!forgotObj.isSuccess()) {
				ToastUtil.showText(getApplicationContext(), forgotObj.getMessage());
				// }
			}

			break;
		}
	}

	public void onCreateAccount(View view) {
		final Intent intent = new Intent(LoginActivity.this, RegistrationActivity.class);
		startActivity(intent);
		finish();
	}

	/** Validate credentials provided */
	private boolean validate(EditText credential) {
		boolean ret = !(credential == null || credential.getText() == null || TextUtils.isEmpty(credential.getText().toString().trim()));
		return ret;
	}

	public void onForgotPassword(View view) {
		// ToastUtil.showNotImplemented(this);
		showDialog(TYPE_EMAIL);
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case TYPE_EMAIL:
			LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = mInflater.inflate(R.layout.forgot_password, null);
			final EditText edtForgot = (EditText) layout.findViewById(R.id.email_forgot);
			edtForgot.setText(username.getText().toString());

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setView(layout);
			builder.setMessage(LoginActivity.this.getResources().getString(R.string.enter_email));

			builder.setPositiveButton(LoginActivity.this.getResources().getString(R.string.send), new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

					Intent forgotPassword = new Intent(Intent.ACTION_SYNC, null, LoginActivity.this, UpdateIntentService.class);
					forgotPassword.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
					forgotPassword.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.FORGOT_PASSWORG);
					forgotPassword.putExtra(Keys._email, edtForgot.getText().toString());
					startService(forgotPassword);

				}
			});
			builder.setNegativeButton(LoginActivity.this.getResources().getString(R.string.cancel), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			builder.setCancelable(true);
			return builder.create();
			// break;

		default:
			break;
		}

		return super.onCreateDialog(id);
	}



	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
			onLoginOnClick(null);
		}
		return false;
	}

}
